﻿using PLC.Application.Recipes.Services;
using PLC.Application.RecipeVariables.Services;
using PLC.Interface.Recipes;
using PLC.Interface.RecipeVariables;
using System.Collections.Generic;
using System.Threading.Tasks;
using YWM;
using YWM.Dto;

namespace PLC.Application.Recipes
{
    public class RecipeAppService : IRecipeAppService
    {
        private readonly IRecipeService _recipeService = YApp.Resolve<IRecipeService>();

        private readonly IRecipeVariableService _recipeVariableService = YApp.Resolve<IRecipeVariableService>();

        public async Task<IReadOnlyList<RecipeResultDto>> GetList(int top = 10)
        {
            PagedResultDto<RecipeResultDto> pagedResultDto = await _recipeService.GetAll(new PagedAndSortedResultRequestDto { MaxResultCount = top });
            return pagedResultDto.Items;
        }

        public async Task<RecipeResultDto> Save(RecipeDto input, List<RecipeVariableDto> recipeVariables)
        {
            RecipeResultDto recipeResultDto = await (input.Id > 0 ? _recipeService.Update(input) : _recipeService.Create(input));
            if (input.Id > 0)
            {
                await _recipeVariableService.Delete(input.Id);
            }
            foreach (RecipeVariableDto recipeVariable in recipeVariables)
            {
                recipeVariable.RecipeId = recipeResultDto.Id;
                await _recipeVariableService.Create(recipeVariable);
            }
            return recipeResultDto;
        }

        public async Task Delete(RecipeDto input)
        {
            await _recipeVariableService.Delete(input.Id);
            await _recipeService.Delete(input);
        }

        public Task Apply(RecipeDto input)
        {
            return _recipeService.Apply(input);
        }
    }
}
